package com.huiyou.control;

import com.github.pagehelper.PageInfo;
import com.huiyou.base.AppBack;
import com.huiyou.model.AdminModel;
import com.huiyou.model.UserModel;
import com.huiyou.service.AdminService;
import com.huiyou.service.UserService;
import com.huiyou.util.StringUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

@Controller
@RequestMapping("/admin")
public class AdminController {


    private Logger logger = Logger.getLogger(AdminController.class);

    @Autowired
    private AdminService adminService;

    @Autowired
    private UserService userService;


    @ExceptionHandler(Exception.class)
    @ResponseBody
    public AppBack<String> exceptionHandler(HttpServletRequest request, Exception e) {
        AppBack<String> appBack = new AppBack<>(-97, "出现异常");

        String info = "";
        Map<String, String[]> map = request.getParameterMap();
        Set<Map.Entry<String, String[]>> set = map.entrySet();
        Iterator<Map.Entry<String, String[]>> it = set.iterator();
        while (it.hasNext()) {
            Map.Entry<String, String[]> entry = it.next();
            info += "  | " + entry.getKey() + "  - ";
            for (String i : entry.getValue()) {
                info += i + "  ";
            }
        }
        appBack.setAction(request.getRequestURI() + info);
        appBack.setResult(e.getMessage());
        logger.error(request.getRequestURI());
        logger.error(e.getMessage(), e);
        return appBack;
    }

    @RequestMapping("/index.html")
    public String index() {
        return "admin/index";
    }

    @RequestMapping("/changePwd.html")
    public String changePwd() {
        return "admin/changePwd";
    }


    @RequestMapping("/modifyPassword")
    public AppBack modifyPassword() {

        return null;
    }


    @RequestMapping("/exit")
    public void exit(HttpServletRequest request, HttpServletResponse response) throws Exception {
        request.getSession().invalidate();
        response.sendRedirect(request.getContextPath() + "/loginAdmin.html");
        return;
    }

    @RequestMapping("/system/getAccountList")//管理员列表列表
    @ResponseBody
    public AppBack getAccountList(@RequestParam(defaultValue = "") String searchKey,
                                  @RequestParam(defaultValue = "") String startTime,
                                  @RequestParam(defaultValue = "") String endTime,
                                  @RequestParam(defaultValue = "") String status,
                                  @RequestParam(defaultValue = "1") int page) {

        Map condition = new HashMap();
        condition.put("noAdmin", 1);
        if (!StringUtil.isEmptyString(searchKey)) {
            condition.put("searchKey", searchKey);
        }
        if (!StringUtil.isEmptyString(startTime)) {
            condition.put("startTime", startTime);
        }
        if (!StringUtil.isEmptyString(endTime)) {
            condition.put("endTime", endTime);
        }
        if (!StringUtil.isEmptyString(status)) {
            condition.put("status", status);
        }

        PageInfo<AdminModel> p = adminService.getList(condition, page);
        return new AppBack(p);
    }

    @RequestMapping("/system/delAccount")//管理员列表列表
    @ResponseBody
    public AppBack getAccountList(int id) {

        return new AppBack(adminService.deleteById(id));
    }

    @RequestMapping("/system/addAccount")
    @ResponseBody
    public AppBack addAccount(@RequestParam(defaultValue = "") String realname,
                              @RequestParam(defaultValue = "") String username,
                              @RequestParam(defaultValue = "") String password,
                              @RequestParam(defaultValue = "0") Integer status) {
        AdminModel adminModel = new AdminModel();
        adminModel.setRealname(realname);
        adminModel.setPassword(password);
        adminModel.setStatus(status);
        adminModel.setUsername(username);
        return new AppBack(adminService.create(adminModel));
    }

    /**
     * 更改管理员状态
     *
     * @param id
     * @param status
     * @return
     */
    @RequestMapping("/system/modifyAccountStatus")
    @ResponseBody
    public AppBack modifyAccountStatus(int id,
                                       int status) {
        AdminModel adminModel = new AdminModel();
        adminModel.setStatus(status);
        adminModel.setId(id);
        return new AppBack(adminService.update(adminModel));
    }

    @RequestMapping("/system/editAccount")
    @ResponseBody
    public AppBack editAccount(int id,
                               String username,
                               String password,
                               String realname,
                               int status) {
        AdminModel adminModel = new AdminModel();
        adminModel.setStatus(status);
        adminModel.setUsername(username);
        if (!StringUtil.isEmptyString(password)) {
            adminModel.setPassword(password);
        }
        adminModel.setRealname(realname);
        adminModel.setId(id);
        return new AppBack(adminService.update(adminModel));
    }

    @RequestMapping("/system/getAccount")
    @ResponseBody
    public AppBack getAccount(int id) {
        return new AppBack(adminService.getById(id));
    }

    @RequestMapping("/system/getAccountChange")
    @ResponseBody
    public AppBack getAccountChange(Integer id) {
        HashMap map = new HashMap();
        map.put("change", 1);
        AdminModel adminModel = adminService.getById(id);

        return new AppBack(adminService.change(adminModel, map));
    }

    @GetMapping("/system/getAccount/{id}")
    @ResponseBody
    public AppBack getAccount(@PathVariable("id") Integer id) {
        return getAccountChange(id);
    }



    @RequestMapping("/user/getUserList")//经销商列表
    @ResponseBody
    public AppBack getUserList(@RequestParam(defaultValue = "") String searchKey,
                               @RequestParam(defaultValue = "") String status,
                               @RequestParam(defaultValue = "1") Integer page) {

        Map condition = new HashMap();
        if (!StringUtil.isEmptyString(searchKey)) {
            condition.put("searchKey", searchKey);
        }

        if (!StringUtil.isEmptyString(status)) {
            condition.put("status", status);
        }

        PageInfo<UserModel> p = userService.getList(condition, page);
        return new AppBack(p);
    }
}
